package com.quick.android.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

public class SimpleUtils {
	public static boolean isDebug = true;
	public static String TAG = "download";

	/** Log打印-d */
	public static void d(String msg) {
		if (isDebug) {
			Log.d(TAG, msg);
		}
	}

	/** Log打印-e */
	public static void e(String msg) {
		if (isDebug) {
			Log.e(TAG, msg);
		}
	}

	/** 获取文件夹名称 */
	public static String getFolderName(String filePath) {

		if (TextUtils.isEmpty(filePath)) {
			return filePath;
		}

		int filePosi = filePath.lastIndexOf(File.separator);
		return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
	}

	/** 创建文件夹 */
	public static boolean makeDirs(String filePath) {
		String folderName = getFolderName(filePath);
		if (TextUtils.isEmpty(folderName)) {
			return false;
		}

		File folder = new File(folderName);
		return (folder.exists() && folder.isDirectory()) ? true : folder
				.mkdirs();
	}

	/** 获取默认扩展缓存目录 */
	public static File getExternalCacheDir(Context context, String dirs_name) {
		File dataDir = new File(new File(
				Environment.getExternalStorageDirectory(), "Android"), "data");
		File appCacheDir = new File(new File(new File(dataDir,
				context.getPackageName()), "cache"), dirs_name);
		if (!appCacheDir.exists()) {
			try {
				new File(dataDir, ".nomedia").createNewFile();
			} catch (IOException e) {
				Log.w("创建目录",
						"Can't create \".nomedia\" file in application external cache directory",
						e);
			}
			if (!appCacheDir.mkdirs()) {
				Log.w("创建目录", "Unable to create external cache directory");
				return null;
			}
		}
		return appCacheDir;
	}

	/**
	 * 文件拷贝
	 */
	public static void copyFile(File sourceFile, File targetFile) {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
			sourceFile.delete();
			sourceFile.deleteOnExit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭流
			try {
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			} catch (IOException e) {
			}
		}
	}
}
